/* eslint-disable react/require-default-props */
/* eslint-disable prefer-destructuring */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 中邮的账号添加、修改
 */
import React, { useState, useCallback, useEffect } from 'react';
import { Modal, Form, Input } from 'antd';
import { connect } from 'dva';
import { password } from '@/components/_utils/rule';
import { phone } from '@/utils/patterns';
import AddressCascader from '@/components/AddressCascader';
import propTypes from 'prop-types';
import TownSelect from './TownSelect';
import { districtIds } from '../utils';

const FormItem = Form.Item;
const titleMap = {
  post: '添加支局',
  yjy: '添加县级网点',
};
const nameMap = {
  post: '中国邮政集团有限公司',
  yjy: '深圳驿加易科技有限公司',
};

const renderFormItem = ({
  getFieldDecorator,
  data: { title, phone: formPhone, name, blank_pwd },
  isXiaoCao,
}) => {
  const allFormItems = [
    {
      belongTo: ['add', 'modify'],
      label: '账号',
      field: 'phone',
      disabled: title === 'modify',
      initialValue: formPhone,
      placeholder: '请输入账号',
      rules: [
        { ...phone },
        {
          required: true,
          message: '请输入账号',
        },
      ],
    },
    {
      belongTo: ['add', 'modify'],
      label: '姓名',
      field: 'name',
      disabled: false,
      initialValue: name,
      placeholder: '请输入姓名',
      rules: [
        {
          max: 20,
        },
        {
          required: true,
          message: '请输入姓名',
        },
      ],
    },
    {
      belongTo: ['add', 'modify'],
      label: '密码',
      field: 'pwd',
      disabled: false,
      initialValue: blank_pwd,
      placeholder: '请输入密码',
      rules: [password],
    },
    {
      belongTo: ['zj', 'zj_edit'],
      label: isXiaoCao ? '加盟商名称' : '支局名称',
      field: 'name',
      disabled: title == 'zj_edit',
      placeholder: isXiaoCao ? '请输入加盟商名称' : '请输入支局名称',
      rules: [
        {
          max: 20,
        },
        {
          required: true,
          message: isXiaoCao ? '请输入加盟商名称' : '请输入支局名称',
        },
      ],
    },
  ];
  return (
    <>
      {allFormItems.map(
        val =>
          val.belongTo.includes(title) && (
            <FormItem label={val.label} key={val.label}>
              {getFieldDecorator(val.field, {
                initialValue: val.initialValue,
                rules: val.rules,
              })(<Input disabled={val.disabled} placeholder={val.placeholder} />)}
            </FormItem>
          ),
      )}
    </>
  );
};

const ZyAdd = props => {
  const {
    dispatch,
    data = {},
    children,
    form,
    getListAfterAdded,
    user,
    updateZJTreeList,
    options: { key } = {},
  } = props;
  const { currentUser = {} } = user;
  const { user_info = {} } = currentUser;
  const { branchName } = user_info;
  const { getFieldDecorator, validateFields, resetFields, setFieldsValue, isFieldsTouched } = form;
  const [visible, setVisible] = useState(false);
  const [branch, setBranch] = useState([]);
  const [branchID, setBranchID] = useState([]);
  const [pid, setPid] = useState();
  const isXiaoCao = branchName.indexOf('小草科技') >= 0;

  useEffect(
    () => {
      if (visible) {
        // 设置当前被编辑账号的所属区域，包括父级数据
        const currentUserLevel = user.currentUser.user_info.branchLevel;
        const currentUserBranch = user.currentUser.user_info.branch || [];
        const isTopAccount = currentUserLevel == 0;

        if (['modify', 'zj_edit'].includes(data.title)) {
          // data.branch为列表账号所传入的，表示当前修改账号所属的区域
          let modifyBranch;
          let modifyId;
          // 当列表数据属于总局时，需要填充数据
          if (isTopAccount && data.branch.length == 0) {
            modifyBranch = [
              {
                id: '0',
                name: nameMap[key],
                level: '0',
                pid: '-2', // 自定义pid用来区分是否是单独属于总公司账号
              },
            ];
            modifyId = ['0'];
          } else {
            // 列表数据不属于总局时，都不需要总局数据去展示
            modifyId = data.branch
              .filter(val => (isTopAccount ? val : val.level != 0))
              .map(i => i.id);
            modifyBranch = data.branch;
          }
          if (data.title == 'zj_edit') {
            const { name, township } = data.branch.find(v => v.level == 4) || {};
            const { id } = data.branch.find(v => v.level == 3) || {};
            setPid(id);
            setTimeout(() => {
              setFieldsValue({ name, township });
            }, 100);
            modifyBranch = modifyBranch.filter(v => v.level != 4);
            modifyId.pop();
          }
          setBranch(modifyBranch);
          setBranchID(modifyId);
        } else if (data.title == 'zj') {
          // 当添加支局时，从用户信息获取所属区域
          // 过滤保存当前区域及下级区域的数据
          const id = currentUserBranch.filter(val => val.level != 0).map(i => i.id);
          const sortBranch = currentUserBranch.filter(val => val.level != 0);
          setBranch(sortBranch);
          setBranchID(id);
        }
      }
    },
    [data.title, data.branch, key, visible],
  );

  const handleOk = useCallback(
    () => {
      validateFields((err, values) => {
        if (err) return;
        const isFormChanged = isFieldsTouched();
        if (!isFormChanged) {
          setVisible(false);
          return;
        }
        const formValues = {
          ...values,
        };
        let type = data.title == 'zj' ? 'accounts/zyAddBranch' : 'accounts/zySave';
        if (data.title == 'modify') {
          delete formValues.phone;
          formValues.uid = data.uid;
          formValues.branch_id = [...values.branch_id].reverse()[0];
        }
        if (data.title == 'zj') {
          formValues.branch_id = [...values.branch_id].reverse()[0];
        }
        if (data.title == 'zj_edit') {
          type = 'accounts/zyEditBranch';
          const { id, pid: _pid } = data.branch.find(v => v.level == 4) || {};
          delete formValues.name;
          formValues.branch_id = _pid;
          formValues.id = id;
          formValues.pid = _pid;
        }
        dispatch({
          type,
          payload: {
            ...formValues,
          },
        }).then(() => {
          resetFields();
          updateZJTreeList && updateZJTreeList(formValues.branch_id); // 更新左侧分公司列表，显示新加的支局
          getListAfterAdded && getListAfterAdded(1, formValues.branch_id);
          setVisible(false);
        });
      });
    },
    [branch, data.branch],
  );

  const handleCancel = useCallback(
    () => {
      resetFields();
      setVisible(false);
    },
    [resetFields],
  );

  const title = t => {
    switch (t) {
      case 'zj':
        return isXiaoCao ? '添加加盟商' : titleMap[key];
      case 'zj_edit':
        return '修改支局';
      case 'add':
        return '添加账号';
      case 'modify':
        return '修改账号';
      default:
        return '';
    }
  };

  const onAddressSelect = (value, selectedOptions) => {
    const { id } = selectedOptions.find(v => v.isLeaf) || {};
    if (districtIds.includes(`${id}`) && data.title == 'zj' && !isXiaoCao) {
      setPid(id);
    } else {
      setPid('');
    }
  };

  return (
    <>
      <span onClick={() => setVisible(true)}>{children}</span>
      <Modal
        destroyOnClose
        width={545}
        centered
        title={title(data.title)}
        visible={visible}
        onCancel={handleCancel}
        onOk={handleOk}
      >
        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} hideRequiredMark>
          <FormItem label="所属区域">
            {getFieldDecorator('branch_id', {
              initialValue: branchID,
              rules: [
                {
                  validator: (rule, value, callback) => {
                    if ((value.length < 3 && data.title == 'zj') || value.length == 0) {
                      callback(rule.message);
                      return;
                    }
                    callback();
                  },
                  message: '请选择所属区域',
                },
              ],
            })(
              <AddressCascader
                disabled={data.title == 'zj_edit'}
                placeholder="请选择所属区域"
                canChooseParent={false}
                level={3}
                type={data.title}
                branch={branch}
                companyId={data.companyId}
                onSelect={onAddressSelect}
                request
              />,
            )}
          </FormItem>
          {pid && (
            <FormItem label="所属乡镇">
              {getFieldDecorator('township')(<TownSelect pid={pid} />)}
            </FormItem>
          )}
          {renderFormItem({ getFieldDecorator, data, isXiaoCao })}
        </Form>
      </Modal>
    </>
  );
};

ZyAdd.propTypes = {
  data: propTypes.object, // title：zj(支局)，modify(编辑)，add(添加账号)，companyId（添加支局时需要）
  getListAfterAdded: propTypes.func, // getListAfterAdded（添加账号后由于刷新列表）
  updateZJTreeList: propTypes.func, // 添加支局后，更新树组件数据，显示新添加的支局数据
};

export default connect(({ user, setting }) => ({ user, ...setting }))(Form.create()(ZyAdd));
